package com.guopiao.vat.common.general.exception;

import com.guopiao.vat.common.general.constants.InvoiceState;
import com.guopiao.vat.common.general.response.GeneralResponse;
import com.guopiao.vat.common.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

/**
 *  
 *  * @Author: Xander Xiao
 *  * @Description: 全局异常捕获
 *  @Date:Create in 2017/12/26
 *  
 */
@ControllerAdvice
@ResponseBody
public class VATGlobalExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(VATGlobalExceptionHandler.class);

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public GeneralResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.error("缺少请求参数，返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"required_parameter_is_not_present"),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"required_parameter_is_not_present");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public GeneralResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("参数解析失败,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"could_not_read_json"),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"could_not_read_json");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public GeneralResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        logger.error("参数验证失败,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),message),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public GeneralResponse handleBindException(BindException e) {
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        logger.error("参数绑定失败,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),message),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public GeneralResponse handleServiceException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        logger.error("参数验证失败,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"parameter:" +message),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"parameter:" +message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public GeneralResponse handleValidationException(ValidationException e) {
        logger.error("参数验证失败,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"validation_exception"),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"validation_exception");
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public GeneralResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("不支持当前请求方法,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"request_method_not_supported"),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"request_method_not_supported");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public GeneralResponse handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.error("不支持当前媒体类型,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"不支持当前媒体类型:request_method_not_supported"),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"不支持当前媒体类型:request_method_not_supported");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(VATException.class)
    public GeneralResponse handleServiceException(VATException e) {
        logger.error("业务逻辑异常,返回信息[{}],异常[{}]", ResponseUtil.error(e.getRequestId(),e.getRtnCode(),e.getMessage()),e);
        return ResponseUtil.error(e.getRequestId(),e.getRtnCode(),e.getMessage());
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public GeneralResponse handleException(Exception e) {
        logger.error("通用异常,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"通用异常"+ e.getMessage()),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"通用异常"+ e.getMessage());
    }

    /**
     * 操作数据库出现异常:名称重复，外键关联
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataIntegrityViolationException.class)
    public GeneralResponse handleException(DataIntegrityViolationException e) {
        logger.error("操作数据库出现异常,返回信息[{}],异常[{}]", ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"操作数据库出现异常：字段重复、有外键关联等"),e);
        return ResponseUtil.error(null,InvoiceState.VALIDATOR.getCode(),"操作数据库出现异常：字段重复、有外键关联等");
    }
}
